#include "form_input.h"
#include "ui_form_input.h"
#include "pub_var.h"

#include <QtDebug>
#include <QScroller>
#include <QMessageBox>
#include <QSqlError>

Form_input::Form_input(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Form_input)
{
    ui->setupUi(this);

    md = new QSqlQueryModel();

qr = new QSqlQuery(pub::db_o);
qr0 = new QSqlQuery(pub::db_o);

ui->tbMode->setTabText(0,"特批");
ui->tbMode->setTabText(1,"邮寄");
ui->tbMode->setTabText(2,"收费");
ui->tbMode->setTabText(3,"补正");

ui->tvList->setFont(this->font());
ui->lwList->setFont(this->font());

    tmr = new QTimer;
    tmrItemDisplay = new QTimer;
    connect(tmr, SIGNAL(timeout()), this, SLOT(tmrTimeout()));
    connect(tmrItemDisplay, SIGNAL(timeout()), this, SLOT(tmrDisplayTimeout()));
    //

    QSettings setIni("clin.ini", QSettings::IniFormat);
    //恢复当前窗口位置
    QRect rct = setIni.value("windowState/tempInput").toRect();
    this->setGeometry(rct);


    QString sq = "select dic_value from drug_sub_dict where dic_type = 'leader'";
    ui->cbbLeader->clear();
    qr->exec(sq);
    while(qr->next()){
        ui->cbbLeader->addItem( qr->value(0).toString() );
    }


    ui->cbbReceiver->clear();
    sq = "select name from drug_post_address order by name";
    qr->exec(sq);
    while (qr->next()) {
        QString itm = qr->value(0).toString();
        ui->cbbReceiver->addItem( itm );
    }
    ui->cbbReceiver->setCurrentIndex(-1);
    ui->tbMode->setCurrentIndex(0);
//QMessageBox::information(NULL,"note","test initialize");
}

Form_input::~Form_input()
{
    delete ui;
}

void Form_input::closeEvent(QCloseEvent *event)
{
    Q_UNUSED(event);
    QSettings setIni("clin.ini", QSettings::IniFormat);
    setIni.setValue("windowState/tempInput", QVariant(this->geometry()));

    emit destroyW( "Form_input" );

    //QMessageBox::information(NULL,"note","emit close signal");
}

void Form_input::on_leSearch_textChanged(QString s)
{

    tmr->start(300);
    //listItems(s.toUpper());

}

void Form_input::listItems(QString s)
{

    QString sq = "select p.TRADE_NAME drug_name, p.specs SPECS, p.DRUG_CODE drug_code, p.PACK_UNIT PACK_UNIT,p.PACK_QTY PACK_QTY,"
                 " d.pym PYM, p.RETAIL_PRICE price, "
                 " nvl(d.recal, 0) RECAL, nvl(d.sub_account, 0) SUB_ACCOUNT"
                 " from pha_com_baseinfo p, drug_base_info d "
                 " where p.drug_code = d.drug_code and d.valid = '1'"
                 " and d.pym like '%" + s + "%' order by p.trade_name, specs";


    md->setQuery(sq, pub::db_o);

    md->setHeaderData(0, Qt::Horizontal, "品名");
    md->setHeaderData(1, Qt::Horizontal, "规格");

    ui->tvList->setModel(md);
    ui->tvList->setColumnWidth(0, ui->tvList->horizontalHeader()->width() * 0.6);
    ui->tvList->setColumnWidth(1, ui->tvList->horizontalHeader()->width() * 0.3);
    ui->tvList->setColumnWidth(2, 0);
    ui->tvList->setColumnWidth(3, 0);
    ui->tvList->setColumnWidth(4, 0);
    ui->tvList->setColumnWidth(5, 0);
    ui->tvList->setColumnWidth(6, 0);
    ui->tvList->setColumnWidth(7, 0);
    ui->tvList->setColumnWidth(8, 0);
    ui->tvList->setColumnWidth(9, 0);

    if( 1 == md->rowCount()){
        QModelIndex idx;
        idx = md->index(0, 0);//
        on_tvList_clicked(idx);
    }

}

void Form_input::on_tvList_clicked(const QModelIndex &index)
{
    mp.clear();
    mp["drug_name"] = index.siblingAtColumn(0).data(0).toString();
    mp["specs"] = index.siblingAtColumn(1).data(0).toString();
    mp["drug_code"] = index.siblingAtColumn(2).data(0).toString();
    mp["pack_unit"] = index.siblingAtColumn(3).data(0).toString();
    mp["pack_qty"] = index.siblingAtColumn(4).data(0).toString();
    mp["store_sum"] = index.siblingAtColumn(5).data(0).toString();
    mp["retail_price"] = index.siblingAtColumn(6).data(0).toString();
//    mp["atinc"] = index.siblingAtColumn(7).data(0).toString();
    ui->leItem->setText( mp["drug_name"] + "/" + mp["specs"] );
    ui->leSum->setText("");
    ui->leSum->setEnabled(true);
    ui->leSum->setFocus();
}

void Form_input::on_tbAdd_clicked()
{
    ui->tbAdd->setEnabled(false);
    if(ui->leItem->text().isEmpty()){
        QMessageBox::warning(this,"注意", "未选定项目！");
        ui->tbAdd->setEnabled(true);
        return;
    }

    int n = ui->leSum->text().toInt();
    if( n <= 0){
        QMessageBox::warning(this,"注意", "数值数据无效！");
        ui->tbAdd->setEnabled(true);
        return;
    }

    mp["apply_sum"] = ui->leSum->text();
    mp["amount"] = QString::number(mp["apply_sum"].toDouble() * mp["retail_price"].toDouble());
    drugList << mp;

    ui->leSearch->setText("");
    //ui->leItem->setText("");
    ui->leSum->setText("");
    itemLength = ui->leItem->text().length();
    tmrItemDisplay->start(30);


    double amount = 0;
    ui->lwList->clear();
        ui->lwList->clear();
        foreach (mp, drugList) {
            amount += mp["amount"].toDouble();
            QString t;
            t.append(mp["drug_name"]);
            t.append(" | ");
            t.append(mp["specs"]);
            t.append(" | ");
            t.append(mp["apply_sum"]);
            t.append(" | ");
            t.append(mp["pack_unit"]);
            ui->lwList->addItem(t);
        }
        ui->leAmount->setText(QString::asprintf("%.2f",amount));
        amountValue = ui->leAmount->text().toDouble()*100;
    ui->leSearch->setFocus();


}

void Form_input::on_pbClear_clicked()
{
    drugList.clear();
    ui->lwList->clear();
    ui->teNote->clear();
    ui->teNoteSell->clear();
    //ui->pteAddress->clear();
    ui->cbbReceiver->setCurrentIndex(-1);
    ui->pteTb1Memo->clear();
    ui->leSearch->setText("");
    ui->leItem->setText("");
    ui->leSum->setText("");
    ui->leSearch->setFocus();
    drugList.clear();
    ui->leAmount->setText("");
    amountValue = 0;
}

void Form_input::clearDrugList()
{
    on_pbClear_clicked();
}


void Form_input::tmrDisplayTimeout()
{

    itemLength -- ;
    QString t = ui->leItem->text();
    t = t.mid(0, itemLength);
    ui->leItem->setText(t);
    if(itemLength <= 0){
        ui->leItem->setText("");
        tmrItemDisplay->stop();
        ui->tbAdd->setEnabled(true);
    }
}

void Form_input::tmrTimeout()
{
    tmr->stop();

    listItems(ui->leSearch->text().trimmed().toUpper());

}

void Form_input::on_tbExit_clicked()
{
    close();
}

void Form_input::on_pbSave_clicked()
{
    if(drugList.isEmpty()){
        QMessageBox::warning(this,"注意", "未录入有效数据！");
        return;
    }

    QString sq;
    switch (ui->tbMode->currentIndex()) {
    case 0:{
        //outWay = "特批";

        inWay = "";
        if(ui->pteTb1Memo->toPlainText().isEmpty()){
           QMessageBox::information(this, "错误" , "备注内容不允许空白！");
           return;
        }

        if(!input("0")){
            return;
        }

        break;
    }
    case 1:{
        //QMessageBox::information(this, "note" ,"not finished");
        outWay = "邮寄";
        inWay = "";
        if(ui->cbbReceiver->currentText().isEmpty()
                || ui->lePhoneNo->text().isEmpty()
                || ui->pteAddress->toPlainText().isEmpty()){
            QMessageBox::information(this, "错误" , "不允许有空白项目！");
            return;
        }

        QString sq = "select name from drug_post_address where name = '" + ui->cbbReceiver->currentText().trimmed() + "'";
        qr->exec(sq);
        if(!qr->next()){
            sq = "insert into drug_post_address (name, phone, address) values('"
                 + ui->cbbReceiver->currentText().trimmed() + "','"
                 + ui->lePhoneNo->text().trimmed() + "','"
                 + ui->pteAddress->toPlainText().trimmed() + "')";
            qr->exec(sq);
        }

        if(!input("1")){
             return;
         }
        break;
    }
    case 2:{

        outWay = "销售";
        inWay = "";



        inCash = ui->leInCash->text().toDouble()*100;
        inMM = ui->leInMM->text().toDouble()*100;
        outCash = ui->leOutCash->text().toDouble()*100;
        outMM = ui->leOutMM->text().toDouble()*100;

        if( outCash < 0 || outMM < 0 || inCash < 0 || inMM < 0 ){
            QMessageBox::information(this, "错误" , "数据关系不合理！");
            return;
        }


        if( outCash + outMM + amountValue != inCash + inMM){
            QMessageBox::information(this, "错误" , "数据关系不合理！");
            return;
        }

        if(!input("2")){
            return;
        }

        break;
    }
    case 3:{
        outWay = "";

        if(ui->radioButton->isChecked()){
            inWay = ui->radioButton->text();
        }else if(ui->radioButton_2->isChecked()){
            inWay = ui->radioButton_2->text();
        }else if(ui->radioButton_3->isChecked()){
            inWay = ui->radioButton_3->text();
        }else if(ui->radioButton_4->isChecked()){
            inWay = ui->radioButton_4->text();
        }else if(ui->radioButton_5->isChecked()){
            inWay = ui->radioButton_5->text();
        }else if(ui->radioButton_6->isChecked()){
            inWay = ui->radioButton_6->text();
        }
        if(!input("3")){
            return;
        }
        //QMessageBox::information(this, "note" ,"not complete");
        break;
    }
    }

    //all procedure is normal.
    emit clearDrugList();
//    close();
}

bool Form_input::input(QString mode)
{
    ui->pbSave->setEnabled(false);
    ui->pushButton->setEnabled(false);
    QString sq;

    QString ld = "";    //leader
    QString memo = "";
    if( "0" == mode){   //特批
        if(ui->rb0->isChecked()){   //
            ld = ui->cbbLeader->currentText();
            outWay = ui->rb0->text();
        }else if(ui->rb1->isChecked()){   //
            //ld = ui->cbbLeader->currentText();
            outWay = ui->rb1->text();
        }else {
            //ld = ui->rb1->text();
            outWay = ui->rb2->text();
        }
        memo = ui->pteTb1Memo->toPlainText();
    }
    if( "1" == mode){   //邮寄
        memo = ui->cbbReceiver->currentText();
        memo.append("/");
        memo.append(ui->lePhoneNo->text());
        memo.append("/");
        memo.append(ui->pteAddress->toPlainText());
    }

    if( "2" == mode){   //零售
        memo = ui->teNoteSell->toPlainText();
    }

    QString sum_str = "";   //补正记负数，其它记正数
    if( "3" == mode){   //补正
        sum_str = " 0 - ";
        memo = ui->teNote->toPlainText();
    }

    sq = "select SEQ_DRUG_SUB_ACCOUNT.NEXTVAL as seq from dual";
    if(!qr->exec(sq)){
        QMessageBox::information(this, "错误" , "取序列号sql语句执行失败！");
        return false;
    }

    if(!qr->next()){
            QMessageBox::information(this, "错误" , "无法读取取序列号！");
            return false;

    }
    //groupNo , combine drug_sub_account to bill_rec if necessary.
    QString groupNo = qr->value(0).toString();
    //QMessageBox::information(this, "错误" , "序列号 : " + groupNo);




    //qr->exec("BEGIN TRANSACTION");

    foreach (mp, drugList) {
        sq = "select SEQ_DRUG_SUB_ACCOUNT.NEXTVAL as seq from dual";
        qr->exec(sq);
        qr->next();
        //groupNo , combine drug_sub_account to bill_rec if necessary.
        QString atinc = qr->value(0).toString();

        sq = "insert into drug_sub_account "
             "(drug_code, drug_name, oper_date, oper_sum, oper_name, leader, memo, out_way, in_way, synchronized, item_io_id, atinc)"
             " values('"
                + mp["drug_code"]
                + "','" + mp["drug_name"]
                + "', sysdate, "
                + sum_str + mp["apply_sum"]
                + ",'" + pub::usr_name
                + "','" + ld
                + "','" + memo
                + "','" + outWay
                + "','" + inWay
                + "','0','" + groupNo
                + "'," + atinc
                +") ";
        qr->prepare(sq);

        if(!qr->exec(sq)){
            QMessageBox::information(this, "错误" , "保存出入库记录错误：\n" + qr->lastError().text() + "\n" + qr->lastQuery());
            ui->pbSave->setEnabled(true);
            ui->pushButton->setEnabled(true);
            return false;
        }
    }
//    qr->exec("COMMIT");

    if( "2" == mode){   //销售

        sq = "insert into bill_rec (item_io_id, cost, in_mmsg, in_cash, out_mmsg, out_cash, oper_name, synchronized)"
             " values ('" + groupNo + "', "
                + (ui->leAmount->text().isEmpty() ? "0" : ui->leAmount->text() ) + ","
                + (ui->leInMM->text().isEmpty() ? "0" : ui->leInMM->text() ) + ","
                + (ui->leInCash->text().isEmpty() ? "0" : ui->leInCash->text() ) + ","
                + (ui->leOutMM->text().isEmpty() ? "0" : ui->leOutMM->text() ) + ","
                + (ui->leOutCash->text().isEmpty() ? "0" : ui->leOutCash->text() ) + ",'"
                + pub::usr_name + "','0') ";
        qr->prepare(sq);
        if(!qr->exec(sq)){
            QMessageBox::information(this, "错误" , "保存收费数据错误：\n" + qr->lastError().text() + "\n" + qr->lastQuery());
            ui->pbSave->setEnabled(true);
            ui->pushButton->setEnabled(true);
            return false;
        }
    }

    ui->pbSave->setEnabled(true);
    ui->pushButton->setEnabled(true);
    return true;
}

void Form_input::on_tbInMM_clicked()
{
    ui->leInMM->setText(ui->leAmount->text());
    ui->leInCash->setText("");
    ui->leOutMM->setText("");
    ui->leOutCash->setText("");

}

void Form_input::on_tbInCash_clicked()
{
    ui->leInCash->setText(ui->leAmount->text());
    ui->leInMM->setText("");
    ui->leOutMM->setText("");
    ui->leOutCash->setText("");

}

void Form_input::on_tbOutCash_clicked()
{
    ui->leOutMM->setText("");

    inMM = ui->leInMM->text().toDouble()*100;
    inCash = ui->leInCash->text().toDouble()*100;
    outCash = inMM + inCash - amountValue ;

    ui->leOutCash->setText(QString::asprintf("%.2f", double(outCash)/100));
}

void Form_input::on_tbOutMM_clicked()
{
    ui->leOutCash->setText("");

    inMM = ui->leInMM->text().toDouble()*100;
    inCash = ui->leInCash->text().toDouble()*100;
    outMM = inMM + inCash - amountValue ;

    ui->leOutMM->setText(QString::asprintf("%.2f", double(outMM)/100));
}

void Form_input::on_toolButton_clicked()
{
    drugList.removeAt(listWidgetRowNum);
    //itemList.removeAt(listWidgetRowNum);
    ui->lwList->clear();

    double amount = 0;
    foreach ( mp, drugList) {
        amount += mp["amount"].toDouble();
        QString t;
        t.append(mp["drug_name"]);
        t.append(" | ");
        t.append(mp["specs"]);
        t.append(" | ");
        t.append(mp["apply_sum"]);
        t.append(" | ");
        t.append(mp["pack_unit"]);

        ui->lwList->addItem(t);
    }

    ui->leAmount->setText(QString::asprintf("%.2f",amount));
    amountValue = ui->leAmount->text().toDouble()*100;

}

void Form_input::on_lwList_clicked(const QModelIndex &index)
{

    listWidgetRowNum = index.row();
    //ui->leItem->setText( ui->lwList->item(listWidgetRowNum)->text());
    //ui->leSum->setText("");
    //ui->leSum->setEnabled(false);

}

void Form_input::on_pushButton_clicked()
{
    close();
}

/*
-- Modify the last number
alter sequence SEQ_DRUG_SUB_ACCOUNT increment by -4 nocache;
select SEQ_DRUG_SUB_ACCOUNT.nextval from dual;
alter sequence SEQ_DRUG_SUB_ACCOUNT increment by 1 cache 20;

-- Create table
create table DRUG_POST_ADDRESS
(
  name    VARCHAR2(20),
  phone   VARCHAR2(20),
  address VARCHAR2(128)
)
tablespace USERS
  pctfree 10
  initrans 1
  maxtrans 255;
*/

void Form_input::on_leSearch_returnPressed()
{
    listItems(ui->leSearch->text().trimmed().toUpper());

}

void Form_input::on_cbbReceiver_currentIndexChanged(const QString &arg1)
{
    QString sq = "select name, phone, address from drug_post_address where name = '" + arg1 + "'";
    qr0->exec(sq);
    qr0->next();
    ui->lePhoneNo->setText( qr0->value(1).toString() );
    ui->pteAddress->clear();
    ui->pteAddress->appendPlainText(qr0->value(2).toString());
    qDebug()<< "cbbReiverText changed.";

}

void Form_input::on_leSum_returnPressed()
{
    on_tbAdd_clicked();
}
